package com.abc.robot01.vivemodel

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abc.robot01.RobotOSApplication
import com.abc.robot01.activity.LoginActivity
import com.abc.robot01.retrofit.RetrofitService
import com.ainirobot.coreservice.client.RobotApi
import com.ainirobot.coreservice.client.listener.CommandListener
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 *   首页登录
 */
class LoginViewModel : ViewModel() {
    val TAG = "LoginViewModel"
    var count by mutableStateOf(0)
        private set

    var sn by mutableStateOf("")
        private set

    var base64 by mutableStateOf("")
        private set

    var debug by mutableStateOf(false)
        private set

    private val _next = MutableLiveData(false)

    val next: LiveData<Boolean> = _next

    init {
        if (RobotOSApplication.ROBOT) {
            RobotApi.getInstance().getRobotSn(object : CommandListener() {
                override fun onResult(result: Int, message: String?, extraData: String?) {
                    super.onResult(result, message, extraData)
                    //取后6位
                    sn = message!!.substring(message.length - 6)
                    Robot.sn = sn
                    check()
                }
            })
        } else {
            Robot.sn = "2674E5"
            sn = Robot.sn
            check()
        }
    }

    fun increment() {
        count++
    }

    fun check() {
        viewModelScope.launch {
            Log.e(LoginActivity.TAG, "SN : " + sn);
            val result2 = RetrofitService.instance.login(sn)
            Log.e(LoginActivity.TAG, "'result:  $result2");
            if (result2.data.userId == null) {
                Log.e(LoginActivity.TAG, "'机器未激活");
                val code = result2.code
                Log.e(LoginActivity.TAG, "'code   $code");
                val qrCode = result2.data.qrCode!!
                Log.e(LoginActivity.TAG, "'qrCode   $qrCode");
                base64 = qrCode

                //以下是持续判断是否注册成功 ,如果成功,则跳转界面,当前界面不用更新
                launch(IO) {
                    while (true) {
                        delay(2000)
                        if (sn.isNotEmpty()) {
                            val result3 = RetrofitService.instance.login(sn)
                            val code2 = result3.code
                            Log.e(LoginActivity.TAG, "'code   $code2");
                            val userId = result3.data.userId
                            Log.e(LoginActivity.TAG, "'持续判断是否注册成功: " + result3);
                            Log.e(LoginActivity.TAG, "userId: " + userId);
                            if (userId != null) {
                                Robot.userId = userId;
                                Robot.companyId = result3.data.companyId
                                Log.e(LoginActivity.TAG, "Robot:" + Robot);
                                _next.postValue(true)
                                break;
                            }
                            increment()
                        }
                    }
                }
            } else {
                Robot.userId = result2.data.userId
                Robot.companyId = result2.data.companyId
                Robot.accessToken = result2.data.accessToken
                Robot.startGetToken()
                Log.e(LoginActivity.TAG, "Robot:" + Robot.toString());
                _next.value = true
            }
        }
    }
}
    object Robot {
        var userId: String = ""

        var accessToken: String = ""

        //    2674E5
        var sn: String = "2674E5"

        var randomId = ""

        var companyId: String = ""

        // Alias using a custom getter
        val robotId: String
            get() = userId

        override fun toString(): String {
            return "userId:$userId,companyId:$companyId,robotId:$robotId"
        }

        suspend fun startGetToken() {
            GlobalScope.launch {
                while (true) {
                    Log.e("RetrofitService'", "开始获取 access_token")
                    val res = RetrofitService.instance.getToken(robotId)
                    Log.e("RetrofitService'", "access_token:" + res)
                    val token = res.data.access_token
                    Log.e("RetrofitService'", "access_token:$token")
                    accessToken = token
                    delay((res.data.expires_in - 100) * 1000L)
                }
            }
        }
    }

